from django.views import View
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from web.utils.tencent.cos import delete_file
from web.utils.tencent.cos import delete_file_list
from web.utils.tencent.cos import credential
from web import models
from web.forms.file import FileFoldForm
import json
import requests
class FileView(View):

    def get(self,request,*args,**kwargs):
        parent_obj = None
        breadcrumb=[]
        fold_id = request.GET.get('folder')
        try:
            if fold_id and fold_id.isdigit():
                parent_obj = models.FileRepository.objects.filter(id=fold_id, project=request.tracer.project).first()
                # parent = parent_obj
                # while parent:
                #     breadcrumb.append({'id': parent.id, 'name': parent.name})
                #     if parent.parent:
                #         parent = parent.parent
                #     else:
                #         break
        except Exception as e:
            print(e)
            print('父文件夹id错误')
            parent_obj = None

        form=FileFoldForm(request=request,parent_obj=parent_obj)
        #查找当前的文件夹
        queryset=models.FileRepository.objects.filter(project=request.tracer.project)

        if parent_obj:
            file_object_list=queryset.filter(parent=parent_obj).order_by('-file_type')
        else:
            file_object_list=queryset.filter(parent__isnull=True).order_by('-file_type')


        return render(request,'manage/file.html',{'form':form,'file_list':file_object_list,'breadcrumb':breadcrumb,'folder':parent_obj})

    def post(self,request,*args,**kwargs):
        parent_obj = None
        fold_id=request.GET.get('folder')
        try:
            if fold_id and fold_id.isdigit():
                parent_obj=models.FileRepository.objects.filter(
                    id=fold_id,
                    project=request.tracer.project).first()
        except Exception as e:
            print(e)
            print('父文件夹id错误')
            parent_obj=None
        id=request.POST.get('id')
        try:
            fileObj=models.FileRepository.objects.filter(id=id).first()
            if fileObj:
                form = FileFoldForm(request=request, parent_obj=parent_obj,instance=fileObj ,data=request.POST)
            else:
                form = FileFoldForm(request=request, parent_obj=parent_obj, data=request.POST)
        except Exception as e:
            form = FileFoldForm(request=request, parent_obj=parent_obj, data=request.POST)
            print(e)

        if form.is_valid():
            form.instance.project=request.tracer.project
            form.instance.file_type = 2
            form.instance.update_user = request.tracer.user
            form.instance.parent=parent_obj
            form.save()
            return JsonResponse({'code':200,'data':'添加成功'})
        else:
            return JsonResponse({'code': 400, 'data': '','error':form.errors})



class FileDeleteView(View):

    def get(self,request,*args,**kwargs):
        id=request.GET.get('id',0)
        try:
            file_obj=models.FileRepository.objects.filter(id=id,project=request.tracer.project).first()
            if file_obj.file_type==1:
                #删除文件

                #项目的已使用空间
                request.tracer.project.use_space-=file_obj.file_size
                request.tracer.project.save()
                # cos 删除
                key=file_obj.key
                bucket=request.tracer.project.bucket
                delete_file(bucket,key)
            else:
                #文件夹
                #文件夹下文件 cos 删除

                total_size=0 #文件
                #文件夹列表
                folder_list=[file_obj,]
                key_list=[]
                for item in folder_list:
                    child_list=models.FileRepository.objects.filter(project=request.tracer.project,parent=item)
                    for child in child_list:
                        if child.file_type == 1:
                            #文件大小汇总
                            total_size+=child.file_size
                            key_list.append({'Key':child.key})
                        else:
                            folder_list.append(child)
                #删除cos 上的文件
                if key_list:
                    bucket = request.tracer.project.bucket
                    delete_file_list(bucket, key_list)
                #更新project中的使用的空间
                request.tracer.project.use_space -= total_size
                request.tracer.project.save()
            file_obj.delete()
            return JsonResponse({'code': 200, 'data': '删除成功'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'data': '','error':e})


@method_decorator(csrf_exempt,name='dispatch')
class CosCredentialView(View):

    def get(self,request,*args,**kwargs):
        try:
            bucket=request.tracer.project.bucket

            config=credential(bucket=bucket)
            return JsonResponse({'status':True,'data':config})
        except Exception as e:
            print('获取cos临时凭证失败')
            print(e)
            return JsonResponse({'code': 400, 'data': '','error':e})
    def post(self,request,*args,**kwargs):
        try:
            print(request.POST)
            bucket=request.tracer.project.bucket

            config=credential(bucket=bucket)
            return JsonResponse({'status':True,'data':config})
        except Exception as e:
            print('获取cos临时凭证失败')
            print(e)
            return JsonResponse({'code': 400, 'data': '','error':e})

@method_decorator(csrf_exempt,name='dispatch')
class FileCheckView(View):

    def post(self,request,*args,**kwargs):
        # 已经使用的大小
        use_space = request.tracer.project.use_space*1024*1024
        # 价格策略中项目的空间大小
        project_space = request.tracer.price_policy.project_space*1024*1024*1024
        # 价格策略中项目的每个文件的大小
        per_file_size = request.tracer.price_policy.per_file_size * 1024 * 1024
        #获取要检查的文件列表
        file_list=json.loads(request.body.decode())

        #要上传文件大小
        total=0
        for item in file_list:
            #单个文件超出限制
            if item['size']>per_file_size:
                return JsonResponse(
                    {'code': 400,
                    'data': '',
                    'error': f'单个文件超标,最大{request.tracer.price_policy.per_file_size} (M),'
                             f'文件:{item["name"]}'})
            else:
                total+=item['size']
        #总共的文件限制
        if total+use_space>project_space:
            return JsonResponse(
                {'code': 400, 'data': '',
                'error': f'总文件超标,'
                         f'项目空间{request.trequest.tracer.price_policy.project_space}(M),'
                         f'已使用:{request.tracer.project.use_space}'})
        #print(f'已用空间大小:{use_space},
        # 价格策略中项目空间大小:{project_space},
        # 单个文件大小:{per_file_size},文件总大小:{total}')
        return JsonResponse({'code': 200, 'data': '', 'error': ''})

@method_decorator(csrf_exempt,name='dispatch')
class FileUploadView(View):
    def post(self,request,*args,**kwargs):
        folder_id=request.GET.get('folder')
        file_list=json.loads(request.body.decode())
        model_list=[]
        for item in file_list:
            if folder_id:
                temp=models.FileRepository(parent_id=folder_id,
                                           file_path=f'{item["Key"]}.cos.ap-beijing.myqcloud.com/{item["Key"]}',
                                           key=item["Key"],
                                           name=item['name'],
                                           file_size=item['size'],
                                           update_user=request.tracer.user,
                                           file_type=1,
                                           project=request.tracer.project)
            else:
                temp=models.FileRepository(
                                           file_path=f'{item["Bucket"]}.cos.ap-beijing.myqcloud.com/{item["Key"]}',
                                           key=item["Key"],
                                           name=item['name'],
                                           file_size=item['size'],
                                           update_user=request.tracer.user,
                                           file_type=1,
                                           project=request.tracer.project)
            model_list.append(temp)
        models.FileRepository.objects.bulk_create(model_list)
        return JsonResponse({'code': 200, 'data': '', 'error': ''})


class FileDownloadView(View):
    def get(self,request,*args,**kwargs):
        '''
        打开文件 获取文件的内容
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        file_id=request.GET.get('id')
        fiel_obj=models.FileRepository.objects.filter(id=file_id,project=request.tracer.project).first()
        file_location=f'https://{fiel_obj.file_path}'
        res=requests.get(file_location)
        data=res.iter_content() #适合大文件
        response=HttpResponse(data)
        response['content-type']='application/octet-stream;charset=utf-8'
        #设置响应头
        #文件名中文转义
        from django.utils.encoding import escape_uri_path
        response['Content-Disposition']=f'attachment;filename={escape_uri_path(fiel_obj.name)}'
        return response